import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useLoadingStore = defineStore('loading', () => {
  const isLoading = ref(false)
  const loadingMessage = ref('')
  const progress = ref(0)
  let timer: number | null = null

  const startLoading = (message?: string) => {
    // 重入保护
    if (isLoading.value) return
    isLoading.value = true
    loadingMessage.value = message || ''
    progress.value = 0

    // 以平滑方式推进至 90%
    const startTime = Date.now()
    const target = 90
    const baseDurationMs = 800 // ~0.8s 推到 90%

    const tick = () => {
      const elapsed = Date.now() - startTime
      const ratio = Math.min(1, elapsed / baseDurationMs)
      const eased = 1 - Math.pow(1 - ratio, 2) // ease-out
      const next = Math.min(target, Math.max(progress.value, Math.floor(eased * target)))
      progress.value = next
      if (progress.value < target && isLoading.value) {
        timer = window.setTimeout(tick, 50)
      }
    }
    timer = window.setTimeout(tick, 16)
  }

  const stopLoading = () => {
    // 立即终止（不做收尾动画）
    isLoading.value = false
    loadingMessage.value = ''
    progress.value = 0
    if (timer) {
      clearTimeout(timer)
      timer = null
    }
  }

  const finishLoading = () => {
    // 推进到 100%，稍后隐藏
    if (timer) {
      clearTimeout(timer)
      timer = null
    }
    progress.value = 100
    // 留一点时间让进度条完成
    window.setTimeout(() => {
      isLoading.value = false
      loadingMessage.value = ''
      progress.value = 0
    }, 200)
  }

  return {
    isLoading,
    loadingMessage,
    progress,
    startLoading,
    stopLoading,
    finishLoading,
  }
}) 